import datetime
from jili.core.convert import str2datetime
from jili.tool import isnumber
from gm import api
api.set_token("ee2553d4a1e522d1cceda05efacd0c2ec0dcbf91")
stock_info={}
def get_info(obj,trade_date=''):
    global stock_info
    gmobj=obj2xtobj(obj)
    if gmobj not in stock_info.keys():
        info=api.get_symbols(1010,symbols=gmobj,trade_date=trade_date)
        if info:
            info=info[0]
            stock_info[gmobj]=info
        else:
            stock_info[gmobj]={"sec_name":""}
            print("get_info err",obj,len(info))
    else:
        info=stock_info[gmobj]
    return info
def get_all_stock():
    global stock_info
    if not stock_info:
        c=api.get_symbols(1010)
        for i in c:
            obj=i["symbol"]
            stock_info[obj]=i
    return stock_info
def get_all_objs():
    global stock_info
    if not stock_info:
        get_all_stock()
    return list(stock_info.keys())
def get_tradeday(count=1):
    now = datetime.datetime.now()
    now=now+datetime.timedelta(days=1)
    d=now.strftime("%Y-%m-%d")
    dt=api.get_previous_n_trading_dates(exchange="SHSE", date=d, n=count)
    tdays = []
    for i in dt:
        tdays.append(str2datetime(i))
    return tdays
def get_tradeday_bydate(end,count=1,start=None):
    if end is None:
        now = str2datetime(start)
        d = now.strftime("%Y-%m-%d")
        dt = api.get_next_n_trading_dates (exchange="SHSE", date=d, n=count)
    elif start is None:
        now = str2datetime(end)
        d = now.strftime("%Y-%m-%d")
        dt = api.get_previous_n_trading_dates(exchange="SHSE", date=d, n=count)
    else:
        start = str2datetime(start)
        start = start.strftime("%Y-%m-%d")
        end = str2datetime(end)
        end = end.strftime("%Y-%m-%d")
        dt=[]
        dt0=api.get_next_n_trading_dates (exchange="SHSE", date=start, n=1)
        while dt0[0]<=end:
            dt.append(dt0[0])
            dt0 = api.get_next_n_trading_dates(exchange="SHSE", date=dt0[0], n=1)
    tdays = []
    for i in dt:
        tdays.append(str2datetime(i))
    return tdays
def istradeday():
    td=get_tradeday()
    now = datetime.datetime.now()
    today = datetime.datetime(now.year, now.month, now.day)
    if today==td[0]:
        return True
    else:
        return False
def obj2xtobj(obj):
    rst = obj
    if isnumber(obj[0]):
        obj=obj.split(".")[0]
        i = obj[0]
        if isnumber(i):
            if i>="5":
                rst="SHSE." + obj
            elif i<="3":
                rst = "SZSE." + obj
    return rst
if __name__=="__main__":
    print(obj2xtobj('600358.SH'))
    print(obj2xtobj('600358'))

